<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>依赖收集 | 掏钱的机器猫</title>
    <meta name="generator" content="VuePress 1.9.7">
    <link rel="icon" href="/vue-admin-ui/assets/logo.png">
    <meta name="description" content="掏钱的机器猫的个人博客,记录随笔与学习笔记，个人项目等">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/vue-admin-ui/assets/css/0.styles.fb55c927.css" as="style"><link rel="preload" href="/vue-admin-ui/assets/js/app.21d1badc.js" as="script"><link rel="preload" href="/vue-admin-ui/assets/js/3.d02ddc64.js" as="script"><link rel="preload" href="/vue-admin-ui/assets/js/1.38c8ef5a.js" as="script"><link rel="preload" href="/vue-admin-ui/assets/js/33.69485516.js" as="script"><link rel="preload" href="/vue-admin-ui/assets/js/8.79ebffb7.js" as="script"><link rel="prefetch" href="/vue-admin-ui/assets/js/10.d9a14dc0.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/11.284df538.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/12.530bdb86.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/13.3dde5c1a.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/14.e18000c4.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/15.65b98979.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/16.953b2589.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/17.d6be13fa.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/18.a10ec5a3.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/19.f2ef083a.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/20.9e024a1a.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/21.b818c6cd.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/22.f3716a62.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/23.42bfb2a3.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/24.0382e6dc.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/25.9b1cf793.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/26.626abbca.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/27.d6b1a7e8.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/28.7381bce0.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/29.65b69672.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/30.70062600.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/31.036bec0e.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/32.1ec26c99.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/34.30a7370c.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/35.1e72f74a.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/36.a6aaafe3.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/4.984f5e20.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/5.2cbf0f84.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/6.eab8daa0.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/7.41bb2a3c.js"><link rel="prefetch" href="/vue-admin-ui/assets/js/9.e9ae19e3.js">
    <link rel="stylesheet" href="/vue-admin-ui/assets/css/0.styles.fb55c927.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container" data-v-2d5f533b><div data-v-2d5f533b><div id="loader-wrapper" class="loading-wrapper" data-v-d48f4d20 data-v-2d5f533b data-v-2d5f533b><div class="loader-main" data-v-d48f4d20><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div></div> <!----> <!----></div> <div class="password-shadow password-wrapper-out" style="display:none;" data-v-64685f0e data-v-2d5f533b data-v-2d5f533b><h3 class="title" style="display:none;" data-v-64685f0e data-v-64685f0e>掏钱的机器猫</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-64685f0e data-v-64685f0e><input type="password" value="" data-v-64685f0e> <span data-v-64685f0e>Konck! Knock!</span> <button data-v-64685f0e>OK</button></label> <div class="footer" style="display:none;" data-v-64685f0e data-v-64685f0e><span data-v-64685f0e><i class="iconfont reco-theme" data-v-64685f0e></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-64685f0e>vuePress-theme-reco</a></span> <span data-v-64685f0e><i class="iconfont reco-copyright" data-v-64685f0e></i> <a data-v-64685f0e><span data-v-64685f0e>Ethan</span>
              
            <span data-v-64685f0e>2018 - </span>
            2022
          </a></span></div></div> <div class="hide" data-v-2d5f533b><header class="navbar" data-v-2d5f533b><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/vue-admin-ui/" class="home-link router-link-active"><img src="/vue-admin-ui/assets/logo.png" alt="掏钱的机器猫" class="logo"> <span class="site-name">掏钱的机器猫</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-document"></i>
        插件文档
      </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/vue-admin-ui-lib/" class="nav-link"><i class="iconfont undefined"></i>
    vue-admin-ui-lib
  </a></li><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/submit-valid/" class="nav-link"><i class="iconfont undefined"></i>
    submit-valid
  </a></li><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/open-utils/" class="nav-link"><i class="iconfont undefined"></i>
    open-utils
  </a></li></ul></div></div><div class="nav-item"><a href="/vue-admin-ui/handle/handle/method.html" class="nav-link"><i class="iconfont undefined"></i>
    手写代码
  </a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-message"></i>
        个人站点
      </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://gitee.com/ethan6" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-mayun"></i>
    Gitee
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://github.com/Ethan66" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <a href="https://github.com/Ethan66/vue-admin-ui" target="_blank" rel="noopener noreferrer" class="repo-link"><i class="iconfont reco-github"></i>
      Github
      <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask" data-v-2d5f533b></div> <aside class="sidebar" data-v-2d5f533b><div class="personal-info-wrapper" data-v-ca798c94 data-v-2d5f533b><img src="/vue-admin-ui/assets/logo.png" alt="author-avatar" class="personal-img" data-v-ca798c94> <h3 class="name" data-v-ca798c94>
    Ethan
  </h3> <div class="num" data-v-ca798c94><div data-v-ca798c94><h3 data-v-ca798c94>24</h3> <h6 data-v-ca798c94>文章</h6></div> <div data-v-ca798c94><h3 data-v-ca798c94>11</h3> <h6 data-v-ca798c94>标签</h6></div></div> <hr data-v-ca798c94></div> <nav class="nav-links"><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-document"></i>
        插件文档
      </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/vue-admin-ui-lib/" class="nav-link"><i class="iconfont undefined"></i>
    vue-admin-ui-lib
  </a></li><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/submit-valid/" class="nav-link"><i class="iconfont undefined"></i>
    submit-valid
  </a></li><li class="dropdown-item"><!----> <a href="/vue-admin-ui/category/open-utils/" class="nav-link"><i class="iconfont undefined"></i>
    open-utils
  </a></li></ul></div></div><div class="nav-item"><a href="/vue-admin-ui/handle/handle/method.html" class="nav-link"><i class="iconfont undefined"></i>
    手写代码
  </a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-message"></i>
        个人站点
      </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://gitee.com/ethan6" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-mayun"></i>
    Gitee
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://github.com/Ethan66" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <a href="https://github.com/Ethan66/vue-admin-ui" target="_blank" rel="noopener noreferrer" class="repo-link"><i class="iconfont reco-github"></i>
      Github
      <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav> <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span></span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/vue-admin-ui/vue/vue/compile.html" class="sidebar-link">compile</a></li><li><a href="/vue-admin-ui/vue/vue/computed.html" class="sidebar-link">computed</a></li><li><a href="/vue-admin-ui/vue/vue/data.html" aria-current="page" class="active sidebar-link">依赖收集</a></li><li><a href="/vue-admin-ui/vue/vue/lifeCycle.html" class="sidebar-link">vue从创建到挂载的过程</a></li><li><a href="/vue-admin-ui/vue/vue/mixins.html" class="sidebar-link">mixins</a></li><li><a href="/vue-admin-ui/vue/vue/watch.html" class="sidebar-link">watch</a></li></ul></section></li></ul> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-64685f0e data-v-2d5f533b><h3 class="title" style="display:none;" data-v-64685f0e data-v-64685f0e>依赖收集</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-64685f0e data-v-64685f0e><input type="password" value="" data-v-64685f0e> <span data-v-64685f0e>Konck! Knock!</span> <button data-v-64685f0e>OK</button></label> <div class="footer" style="display:none;" data-v-64685f0e data-v-64685f0e><span data-v-64685f0e><i class="iconfont reco-theme" data-v-64685f0e></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-64685f0e>vuePress-theme-reco</a></span> <span data-v-64685f0e><i class="iconfont reco-copyright" data-v-64685f0e></i> <a data-v-64685f0e><span data-v-64685f0e>Ethan</span>
              
            <span data-v-64685f0e>2018 - </span>
            2022
          </a></span></div></div> <div data-v-2d5f533b><main class="page"><div class="page-title" style="display:none;"><h1 class="title">依赖收集</h1> <div data-v-3b7f5bdf><i class="iconfont reco-account" data-v-3b7f5bdf><span data-v-3b7f5bdf>Ethan</span></i> <i class="iconfont reco-date" data-v-3b7f5bdf><span data-v-3b7f5bdf>2020-10-23</span></i> <!----> <i class="iconfont reco-tag tags" data-v-3b7f5bdf><span class="tag-item" data-v-3b7f5bdf>vue2源码</span></i></div></div> <div class="theme-reco-content content__default" style="display:none;"><h1 id="依赖收集"><a href="#依赖收集" class="header-anchor">#</a> 依赖收集</h1> <h2 id="数据初始化"><a href="#数据初始化" class="header-anchor">#</a> 数据初始化</h2> <p><a href="https://cloud.tencent.com/developer/article/1479270" target="_blank" rel="noopener noreferrer">基本数据类型<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> <a href="https://cloud.tencent.com/developer/article/1479267" target="_blank" rel="noopener noreferrer">引用类型<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> <a href="https://cloud.tencent.com/developer/article/1479254" target="_blank" rel="noopener noreferrer">依赖更新<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p> <ul><li>代码: vue-learn-code/Vue2.5.16/depend_collection.html。</li></ul> <blockquote><p>vue初始化，先执行vm._init()方法，执行mergeOptions()方法，生成新的data()函数。然后执行initData()方法，执行新的data（将mixins和当前组件的data函数执行再合并）,返回的对象存入vm._data中，再执行proxy()将vm._data进行代理，可以直接用vm.data访问。再执行observe()对数据进行响应式。创建Observer实例，将observer实例赋值给对象的__ob__属性，证明这个对象是已经做了响应式的。再判断对象是数组还是对象，对象的话遍历属性，执行defineReactive()，并对每个属性创建Dep实例，递归设置get，set，假如value还是对象，递归执行observe()。Dep实例赋值给observe实例的dep属性。对象数组有__ob__属性，基本类型没有。</p></blockquote> <h2 id="mergeoptions"><a href="#mergeoptions" class="header-anchor">#</a> mergeOptions()</h2> <ul><li>options.extends存在时，执行parent = mergeOptions(parent, options.extends, vm)</li> <li>options.mixins存在时, 遍历options.mixins，循环执行parent = mergeOptions(parent, child.mixins[i], vm)</li> <li>设置变量options对象</li> <li>遍历parent，执行mergeField(key)，返回值给options[key]</li> <li>遍历options，执行mergeField(key)，key为parent不存在的key，返回值给options[key]，此时data变为mergedInstanceDataFn新函数</li> <li>返回options，给vm.$options，跳出函数</li></ul> <h3 id="parent的mergefield-key"><a href="#parent的mergefield-key" class="header-anchor">#</a> parent的mergeField(key)</h3> <ul><li>options.extends和options.mixins都不存在时，parent的属性为_base, components, directives, filters</li></ul> <h3 id="options的mergefield-key"><a href="#options的mergefield-key" class="header-anchor">#</a> options的mergeField(key)</h3> <h2 id="initdata-vm"><a href="#initdata-vm" class="header-anchor">#</a> initData(vm)</h2> <ul><li>执行$options.data()，返回的对象传给vm._data</li> <li>遍历vm._data属性key，执行proxy(vm, '_data', key)，进行数据代理</li> <li>observe(vm._data), （递归拦截：假如不是数组对象，直接return出去，跳出observe()）。进行数据响应化，判断vm._data是否存在vm._data.__ob__属性，存在表示已经进行数据响应化过，直接返回vm._data.__ob__的value，否则执行new Observer(vm._data)</li></ul> <h3 id="options-data实现"><a href="#options-data实现" class="header-anchor">#</a> $options.data实现</h3> <div class="code-wrap"><!----> <div class="code--demo"><div class="code-content"><div>1、options只有data属性，返回值为option.data.call(vm, vm)。2、options有data和mixins属性，函数执行顺序为data(), mixins数组是倒序执行data()。权重是：data()最大，mixins数组后面的权重比前面大（和函数执行顺序相反，因为函数先执行的后合并对象）</div> <div class="code-tips"></div></div></div> <div class="code--segment"><highlight-code lang="js">
    // demo
    var parent = {}
    var child = {
      data () { console.log('a'); return { a: 1 } },
      mixins: [{ data () {
        console.log('b');
        return { b: 2 }
      } }, {
        data () {
          console.log('c');
          return { c: 3 }
        }
      }]
    }
    var result = mergeOptions(parent, child, window)
    console.log(result.data())
<div class="language- extra-class"><pre><code>// function: 模拟函数
function mergeOptions (parent, child, vm) {
  if (child.mixins) {
    child.mixins.forEach(item =&gt; {
      parent = mergeOptions(parent, item, vm)
    })
  }
  let options = {}
  for(let key in parent) {
    options[key] = mergeField(key, parent, child, vm)
  }
  for(let key in child) {
    if (!parent[key]) {
      options[key] = mergeField(key, parent, child, vm)
    }
  }
  return options
}

function mergeField(key, parent, child, vm) {
  if (key === 'data') {
    return function mergedInstanceDataFn() {
      var instanceData = child[key] &amp;&amp; child[key].call(vm, vm)
      var defaultData = parent[key] &amp;&amp; parent[key].call(vm, vm)
      if (instanceData) {
        return mergeData(instanceData, defaultData)
      } else {
        return defaultData
      }
    }
  }
}

function mergeData (to, from) {
  if (!from) {
    return to
  }
  for(let key in from) {
    if (!to.hasOwnProperty(key)) {
      to[key] = from[key]
    }
  }
  return to
}
</code></pre></div></highlight-code></div> <div class="code--button">显示代码</div></div> <h3 id="proxy实现"><a href="#proxy实现" class="header-anchor">#</a> proxy实现</h3> <div class="code-wrap"><!----> <div class="code--demo"><div class="code-content"><div>proxy(vm, '_data', key)</div> <div class="code-tips"></div></div></div> <div class="code--segment"><highlight-code lang="js">
    var sharedPropertyDefinition = { //共享属性定义
        enumerable: true,
        configurable: true,
        get: function(){},
        set: function(){}
    };
    function proxy(target, sourceKey, key) {
        sharedPropertyDefinition.get = function proxyGetter() { //设置get函数
            return this[sourceKey][key]
        };
        sharedPropertyDefinition.set = function proxySetter(val) {//设置set函数
            this[sourceKey][key] = val;
        };
        Object.defineProperty(target, key, sharedPropertyDefinition); //设置监听观察者
    }
  </highlight-code></div> <div class="code--button">显示代码</div></div> <h3 id="new-observer-vm-data"><a href="#new-observer-vm-data" class="header-anchor">#</a> new Observer(vm._data)</h3> <ul><li>new Observer(vm._data)，this就是实例</li> <li>将vm._data赋值给this.value, new Dep()赋值给this.dep, 将this绑定到vm._data.__ob__上。所以最后的vm._data的属性有$options.data()里的属性，还有vm._data.__ob__属性，vm._data.__ob__属性里有value属性和dep属性。而且vm._data.obj是对象数组的话，vm._data.obj.__ob__属性有value属性和dep属性。</li> <li>vm._data是对象, 遍历每一个属性，执行<code>definReactive(vm._data, key)</code></li> <li>vm._data是数组，改变数组的原型对象，当执行数组方法的时候调用新的方法，再遍历属性进行递归observe()</li></ul> <h4 id="definreactive-vm-data-key"><a href="#definreactive-vm-data-key" class="header-anchor">#</a> definReactive(vm._data, key)</h4> <ul><li>dep = new Dep()。</li> <li>Object.getOwnpropertyDescriptor(vm._data, key)， 保存原有的getter和setter属性</li> <li>递归执行observe(vm._data.key)，获得childOb</li> <li>Object.defineProperty(vm._data, key)，设置get，set属性</li> <li>get属性：判断原有的getter存在，存在：执行getter.call(vm.<em>data)|| vm.<em>data.key生成value，判断Dep.target是否存在（此时用到的watcher实例），执行dep.depend()，将Dep.target的watcher实例添加到dep数组中。判断子对象childObj是否存在，是执行childObj.dep.depend()，将Dep.target的watcher传给子对象（这样页面使用了对象a，对象a通过$set新增了属性，a.<strong>ob</strong>.dep.notify执行，更新了页面P）。判断value是否是数组，是执行dependArray(value)，将Dep.target的watcher添加给value数组（数组是重写了数组方法，数组方法触发了，执行__ob</em></em>.dep.notify()，所以需要将Dep.target的watcher添加给数组的__ob__.dep中）。</li> <li>set属性：传入的新的值newValue，判断原有的getter存在，存在：执行getter.call(vm._data)|| vm._data.key生成value，判断value和newValue是否相同，相同直接跳出。存在原有的setter属性，执行setter.call(wm._data.key, newValue)。再怼newValue进行数据响应式: observe(newValue)，最后dep.notify()：遍历执行dep数组的watcher的update，执行更新</li> <li>get属性的注意点：比如vm._data = {a: {b: 1}}，页面P使用了vm.a和vm.a.b，此时的Dep.target为P的watcher。1、获取vm.a执行a属性的get函数，调用dep.depend()，将P的watcher传入<code>闭包中的dep（不是__ob__.dep）</code>；2、<code>获取vm.a.b，不是直接执行b属性的get函数，因为要先获取vm.a的值，所以要先执行a属性的get函数</code>，此时dep.depend()判断watcher.id是否重复，重复就不保存到dep数组中。</li> <li>set属性的注意点：<code>dep.notify()中的dep都是闭包中的dep，不是this.dep</code>。</li> <li>更新的时候：页面P1使用了vm.a，页面P2使用了vm.a.b，所以a属性中的dep保存了P1的watcher和P2的watcher。b属性的dep保存了P2的watcher。改变vm.a，更新了P1和P2。改变vm.a.b，只更新P2。</li></ul> <h4 id="definreactive实现"><a href="#definreactive实现" class="header-anchor">#</a> definReactive实现</h4> <div class="code-wrap"><!----> <div class="code--demo"><div class="code-content"><div>observe(vm._data)实现，new Observer(vm._data)实现， defineReactive(vm._data, key)实现</div> <div class="code-tips"></div></div></div> <div class="code--segment"><highlight-code lang="js">
    function observe(value) {
      if (typeof value !== 'object') return // 递归拦截：假如不是对象，直接返回
      var ob
      if (value.__ob__) {
        ob = value.__ob__ // __ob__为数据响应标识，直接返回
      } else {
        ob = new Observer(value)
      }
      return ob
    }
<div class="language- extra-class"><pre><code>function Observer(value) {
  this.value = value // 将vm._data存在this.value中
  this.dep = new Dep() // 创建Dep实例，存在this.dep中
  Object.defineProperty(value, '__ob__', { // 标识__ob__，说明已经数据响应了
    enumerable: false,
    configurable: true,
    writable: true,
    value: this
  })
  if (Array.isArray(value)) { // 数组:改变数组的原型对象，再遍历属性进行递归observe()
    
  } else {
    Object.keys(value).forEach(key =&gt; { // 对象，遍历属性，开始响应式
      defineReactive(value, key, value[key])
    })
  }
}

function defineReactive(obj, key, val) {
  let dep = new Dep() // 每个属性创建Dep实例
  let property = Object.getOwnPropertyDescriptor(obj, key)
  let getter = property &amp;&amp; property.get
  let setter = property &amp;&amp; property.set
  var childOb = observe(val) // 递归对象的每个属性，返回__ob__对象
  var value = getter ? getter.call(obj) : val
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      if (Dep.target) { // 静态
        dep.depend()
        if (childOb) {
          childOb.dep.depend() // 存在每个对象的__ob__.dep中，调用vue.$set和vue.$del使用__ob__.dep触发更新
          if (Array.isArray(value)) { // 数组
            dependArray(value)
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      if (newVal === value) {
        return
      }
      if (setter) {
        setter.call(obj, newVal)
      } else {
        value = newVal
      }
      observe(newVal) // 赋值的新对象进行数据响应化
      dep.notify() // 遍历触发watcher.updater()
    }
  })
}

function Dep() {
  this.subs = []
}
// 收集watcher
Dep.prototype.depend = function () {
  if (this.subs.find(dep =&gt; dep.id !== Dep.target.id)) {
    this.subs.push(Dep.target)
  }
}
// 更新watcher.updater方法
Dep.prototype.notify = function () {
  this.subs.forEach(item =&gt; item.updater())
}

// demo1: vm._data只有一级，页面A使用了a属性
var vm1 = { _data: { a: 1 } }
observe(vm1._data)
var result1 = vm1._data
console.log('数据响应后的vm._data：', result1)
Dep.target = {
  title: '我是页面A的water',
  id: '1',
  updater: function () { console.log('我要更新' + this.title.slice(2, 5)) }
}

console.log('我开始收集使用a属性的watcher: ', result1.a)
console.log('我修改了数据开始更新watcher.updater()：')
result1.a = 2
</code></pre></div></highlight-code></div> <div class="code--button">显示代码</div></div> <h2 id="依赖如何收集"><a href="#依赖如何收集" class="header-anchor">#</a> 依赖如何收集</h2> <p>页面P使用的数据D，渲染P的时候先将模板字符串转为render函数，执行render函数的时候获取D，执行Object.defineProperty.get方法，此时的Dep.target指向P的watcher,此时数据D就收集Dep.target，执行Dep.addSub函数，将watcher存到dep实例的subs数组里。</p> <h2 id="如果页面p只使用了数据d-为什么修改d里对象的属性a时-也会更新页面"><a href="#如果页面p只使用了数据d-为什么修改d里对象的属性a时-也会更新页面" class="header-anchor">#</a> 如果页面P只使用了数据D，为什么修改D里对象的属性a时，也会更新页面</h2> <p>页面渲染的时候是字符串模板，执行vm._render函数的时候，先找到数据D，然后再去找数据a，所以虽然P只使用了数据D，但是获取的值，不仅获取了数据D还获取了数据D.a，所以修改D.a，会触发D.a的闭包dep变量的notify()方法，遍历执行watcher.updater()，然后页面P的修改。</p></div> <footer class="page-edit" style="display:none;"><!----> <div class="last-updated"><span class="prefix">上次更新: </span> <span class="time">2022/7/8 上午10:51:20</span></div></footer> <!----> <!----> <!----></main> <!----></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div></div></div>
    <script src="/vue-admin-ui/assets/js/app.21d1badc.js" defer></script><script src="/vue-admin-ui/assets/js/3.d02ddc64.js" defer></script><script src="/vue-admin-ui/assets/js/1.38c8ef5a.js" defer></script><script src="/vue-admin-ui/assets/js/33.69485516.js" defer></script><script src="/vue-admin-ui/assets/js/8.79ebffb7.js" defer></script>
  </body>
</html>
